//
//  KeHuYeShaiXuanView.m
//  JuBoCRM
//
//  Created by iMac on 2024/2/5.
//  Copyright © 2024 iningKe. All rights reserved.
//

#import "KeHuYeShaiXuanView.h"
#import <UITableView+FDTemplateLayoutCell.h>
#import "HomePageSouSuoHeaderView.h"
#import "KeHuQuYuTableViewCell.h"
#import "BRAddressPickerView.h"
#import "NSDate+Helper.h"
@implementation KeHuYeShaiXuanView{
    NSMutableArray *dataSource;
    NSArray *origonArray;
    NSDictionary *paiXunDic;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (void)awakeFromNib{
    [super awakeFromNib];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    
    if (@available(iOS 11.0, *)) {
        self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    if (@available(iOS 15.0, *)) {
        self.mainTableView.sectionHeaderTopPadding = 0 ;
    } else {
        // Fallback on earlier versions
    }
    [_mainTableView registerNib:[UINib nibWithNibName:@"SearchTableViewCell" bundle:nil] forCellReuseIdentifier:@"searchCell"];
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"KeHuQuYuTableViewCell" bundle:nil] forCellReuseIdentifier:@"KeHuQuYuTableViewCell"];
    
    
    _bottomView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.1600].CGColor;
    _bottomView.layer.shadowOffset = CGSizeMake(0,0);
    _bottomView.layer.shadowOpacity = 1;
    _bottomView.layer.shadowRadius = 8;
    
    
    [self shiJianPaiXu:nil];
    
    [self getInfoFromServer];
    

}

- (void)getInfoFromServer{
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:@"2" forKey:@"label"];
    [[ZZPRequest getWebUtil] postNetworkRequestURLString:@"/crmScene/queryField" andParas:paraDic andShowHud:nil andTransferGottenData:^(id info, NSError *error) {
        if(!error){

            origonArray = [info objectForKey:@"data"];
            
            [self zuZhuangShuJu];
           
        }
    }];
}

//组装数据
- (void)zuZhuangShuJu{
//    NSArray *array = @[@"客户阶段",@"地区定位",@"客户类型",@"纠纷类型",@"客户行业",@"员工与部门"];
    NSArray *array = @[@"level",@"address",@"fliedMjrdbe",@"fliedMtfnrf",@"industry",@"员工与部门"];
    dataSource = [NSMutableArray array];
    for (NSString *name in array) {
        NSDictionary *dataDic = [self huoQuShuJuDicWithName:name andArray:origonArray];
        [dataSource addObject:dataDic];
    }
    [_mainTableView reloadData];
}

//获取后台设置的数据
- (NSDictionary *)huoQuShuJuDicWithName:(NSString *)name andArray:(NSArray *)array{
    NSDictionary *tempDic = [NSDictionary dictionary];
    for (NSDictionary *dataDic in array) {
        if([GetHandleString(dataDic, @"fieldName") isEqualToString:name]){
            tempDic = dataDic;
            break;
        }
    }
    return tempDic;
}

- (void)setBuMenChangYuan:(NSString *)buMenChangYuan{
    _buMenChangYuan = buMenChangYuan;
    
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:dataSource[5]];
    [dataDic setValue:buMenChangYuan forKey:@"value"];
    [dataSource replaceObjectAtIndex:5 withObject:dataDic];
    
    [UIView performWithoutAnimation:^{
        [_mainTableView reloadData];
    }];
}



//时间排序
- (IBAction)shiJianPaiXu:(UIButton *)sender {
    NSArray *array = @[@{@"order":@"1",@"sortField":@"createTime"},@{@"order":@"2",@"sortField":@"createTime"},@{@"order":@"1",@"sortField":@"lastContent"},@{@"order":@"2",@"sortField":@"lastContent"}];
    for (NSInteger i =100; i < 104; i++) {
        UIButton *button = [self viewWithTag:i];
        if(sender.tag == i){
            [button setTitleColor:rgba(34, 99, 225, 1) forState:UIControlStateNormal];
            [button setBackgroundColor:rgba(242, 247, 255, 1)];
            button.layer.borderColor = [rgba(40, 120, 255, 1) CGColor];
            button.layer.borderWidth = 0.5f;
            paiXunDic = array[i-100];
        }else{
            [button setTitleColor:rgba(163, 168, 185, 1) forState:UIControlStateNormal];
            [button setBackgroundColor:rgba(247, 248, 250, 1)];
            button.layer.borderColor = [rgba(247, 248, 250, 1) CGColor];
            button.layer.borderWidth = 0.5f;
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    HomePageSouSuoHeaderView *header = [HomePageSouSuoHeaderView view];
    header.titleLabel.text = @[@"客户阶段",@"地区定位",@"客户类型",@"纠纷类型",@"客户行业",@"员工与部门"][section];
    return header;
}

#pragma mark ========== tableview侧滑删除 S===================

#pragma mark ========== tableview侧滑删除 E===================

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
 
    return 42;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 6;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if(indexPath.section == 1 || indexPath.section == 5){
        NSDictionary *dataDic = dataSource[indexPath.section];
        KeHuQuYuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KeHuQuYuTableViewCell"];
        if(indexPath.section == 1){
            cell.leftSpace.constant = 36;
            cell.dingWeiImage.hidden = NO;
            cell.insertTextField.placeholder = @"请选择地区定位";
        }else{
            cell.leftSpace.constant = 16;
            cell.dingWeiImage.hidden = YES;
            cell.insertTextField.placeholder = @"请选择员工与部门";
        }
        cell.insertTextField.text = GetHandleString(dataDic, @"value");
        return cell;
    }
    
    SearchTableViewCell *searchCell = [tableView dequeueReusableCellWithIdentifier:@"searchCell"];
    searchCell.backgroundColor = [UIColor whiteColor];
    [self configCell:searchCell indexpath:indexPath];
    return searchCell;
}
- (void)configCell:(SearchTableViewCell *)cell indexpath:(NSIndexPath *)indexpath{
    
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:dataSource[indexpath.section]];
    
    NSArray *array = [dataDic objectForKey:@"setting"];
    
    [cell.tagView removeAllTags];
    cell.tagView.backgroundColor = [UIColor whiteColor];
    cell.tagView.preferredMaxLayoutWidth = [UIScreen mainScreen].bounds.size.width;
    cell.tagView.padding = UIEdgeInsetsMake(6,16, 6, 16);
    cell.tagView.lineSpacing = 16;
    cell.tagView.interitemSpacing = 16;
    cell.tagView.singleLine = NO;
  
    cell.tagView.regularHeight = 28;

    if(indexpath.section == 0){
        cell.tagView.regularWidth = (ScreenWidth-16*3)/2.0;
    }else{
        cell.tagView.regularWidth = (ScreenWidth-16*4-1)/3.0;
    }
    
    
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SKTag *tag = [[SKTag alloc] initWithText:array[idx]];
        tag.font = [UIFont systemFontOfSize:14];
        tag.cornerRadius = 5;
        tag.enable = YES;
        
        
        if([GetHandleString(dataDic, @"value") isEqualToString:array[idx]]){
            tag.buttonStyle = 2;
        }else{
            tag.buttonStyle = 1;
        }
        
        
        tag.padding = UIEdgeInsetsMake(5, 12, 5, 12);
        [cell.tagView addTag:tag];
    }];
    
    cell.tagView.didTapTagAtIndex = ^(NSUInteger index){
        [dataDic setValue:array[index] forKey:@"value"];
        [dataSource replaceObjectAtIndex:indexpath.section withObject:dataDic];
        [UIView performWithoutAnimation:^{
            [_mainTableView reloadData];
        }];
    };
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 1 || indexPath.section == 5){
        return 66;
    }
    
    return [tableView fd_heightForCellWithIdentifier:@"searchCell" configuration:^(id cell) {
        
        [self configCell:cell indexpath:indexPath];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 1){
        BRAddressPickerView *addressPickerView = [[BRAddressPickerView alloc]init];
        addressPickerView.pickerMode = BRAddressPickerModeArea;
        addressPickerView.title = @"";
        addressPickerView.isAutoSelect = NO;
        addressPickerView.selectIndexs = self.addressSelectIndexs;
        addressPickerView.resultBlock = ^(BRProvinceModel *province, BRCityModel *city, BRAreaModel *area) {
            self.addressSelectIndexs = @[@(province.index), @(city.index), @(area.index)];
            self.addressSelectValues = @[province.name, city.name, area.name];
            NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:dataSource[indexPath.section]];
            [dataDic setValue:[NSString stringWithFormat:@"%@,%@,%@",province.name,city.name,area.name] forKey:@"value"];
            [dataSource replaceObjectAtIndex:indexPath.section withObject:dataDic];

            [UIView performWithoutAnimation:^{
                [_mainTableView reloadData];
            }];
        };
        BRPickerStyle *customStyle = [[BRPickerStyle alloc]init];
        customStyle.pickerColor = [UIColor whiteColor];
        customStyle.selectRowTextColor = rgba(51, 51, 51, 1);
        customStyle.titleBarColor = [UIColor whiteColor];
        customStyle.titleTextColor = [UIColor whiteColor];
        customStyle.cancelTextColor = rgba(153, 153, 153, 1);
        customStyle.doneTextColor = rgba(40, 120, 255, 1);
        customStyle.titleBarHeight = 48;
        customStyle.titleTextFont = [UIFont systemFontOfSize:18];
        addressPickerView.pickerStyle = customStyle;
        customStyle.topCornerRadius = 10;
        customStyle.hiddenTitleLine = YES;
        customStyle.separatorColor = rgba(223, 229, 242, 1);
        customStyle.separatorHeight = 0.5;
        customStyle.rowHeight = 64;

        [addressPickerView show];
    }else if (indexPath.section == 5){
//        员工与部门
        if(_toSelectYuanGongBuMenBlock){
            _toSelectYuanGongBuMenBlock();
        }
    }
    
}


//重置
- (IBAction)chongZhi:(UIButton *)sender {
    [self zuZhuangShuJu];
    [self shiJianPaiXu:nil];
    self.addressSelectValues = [NSArray array];
    _chuangJianJieShuTf.text = nil;
    _chuangJianKaiShiTf.text = nil;
    _genJinJieShuTf.text = nil;
    _genJinKaiShiTf.text = nil;
    _chengYuanArray = [NSArray array];
    _buMenArray = [NSArray array];
    paiXunDic = [NSDictionary dictionary];
}

//确定
- (IBAction)quDing:(UIButton *)sender {
    
    
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionaryWithDictionary:paiXunDic];
    
    
    NSMutableArray *array = [NSMutableArray array];
    
//    创建时间
    if(_chuangJianKaiShiTf.text.length > 0 && _chuangJianJieShuTf.text.length > 0){
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setValue:@"datetime" forKey:@"formType"];
        [dataDic setValue:@"createTime" forKey:@"name"];
        [dataDic setValue:@"14" forKey:@"type"];
        [dataDic setValue:@[_chuangJianKaiShiTf.text,_chuangJianJieShuTf.text] forKey:@"values"];
        [array addObject:dataDic];
    }
//    跟进时间
    if(_genJinKaiShiTf.text.length > 0 && _genJinJieShuTf.text.length > 0){
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setValue:@"datetime" forKey:@"formType"];
        [dataDic setValue:@"lastTime" forKey:@"name"];
        [dataDic setValue:@"14" forKey:@"type"];
        [dataDic setValue:@[_genJinKaiShiTf.text,_genJinJieShuTf.text] forKey:@"values"];
        [array addObject:dataDic];
    }
 
//    客户阶段
    NSDictionary *jieDuanDic = [self huoQuShuJuDicWithName:@"level" andArray:dataSource];
    if([GetHandleString(jieDuanDic, @"value") length] > 0){
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setValue:@"select" forKey:@"formType"];
        [dataDic setValue:@"level" forKey:@"name"];
        [dataDic setValue:@"1" forKey:@"type"];
        [dataDic setValue:@[GetHandleString(jieDuanDic, @"value")] forKey:@"values"];
        [array addObject:dataDic];
    }
    //    地区定位
    if(self.addressSelectValues.count > 0){
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setValue:@"map_address" forKey:@"formType"];
        [dataDic setValue:@"address" forKey:@"name"];
        [dataDic setValue:@"1" forKey:@"type"];
        [dataDic setValue:self.addressSelectValues forKey:@"values"];
        [array addObject:dataDic];
    }
    //    客户类型
    NSDictionary *keHuLeiXingDic = [self huoQuShuJuDicWithName:@"fliedMjrdbe" andArray:dataSource];
    if([GetHandleString(keHuLeiXingDic, @"value") length] > 0){
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setValue:@"select" forKey:@"formType"];
        [dataDic setValue:@"fliedMjrdbe" forKey:@"name"];
        [dataDic setValue:@"1" forKey:@"type"];
        [dataDic setValue:@[GetHandleString(keHuLeiXingDic, @"value")] forKey:@"values"];
        [array addObject:dataDic];
    }
    
    //    纠纷类型
    NSDictionary *jieFenLeiXingDic = [self huoQuShuJuDicWithName:@"fliedMtfnrf" andArray:dataSource];
    if([GetHandleString(jieFenLeiXingDic, @"value") length] > 0){
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setValue:@"select" forKey:@"formType"];
        [dataDic setValue:@"fliedMtfnrf" forKey:@"name"];
        [dataDic setValue:@"1" forKey:@"type"];
        [dataDic setValue:@[GetHandleString(jieFenLeiXingDic, @"value")] forKey:@"values"];
        [array addObject:dataDic];
    }
    //客户行业
    NSDictionary *keHuHangYeDic = [self huoQuShuJuDicWithName:@"industry" andArray:dataSource];
    if([GetHandleString(keHuHangYeDic, @"value") length] > 0){
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setValue:@"select" forKey:@"formType"];
        [dataDic setValue:@"industry" forKey:@"name"];
        [dataDic setValue:@"1" forKey:@"type"];
        [dataDic setValue:@[GetHandleString(keHuHangYeDic, @"value")] forKey:@"values"];
        [array addObject:dataDic];
    }
    
    //    部门
    if(_buMenArray.count > 0){
        NSMutableArray *temp = [NSMutableArray array];
        for (NSDictionary *tempD in _buMenArray) {
            [temp addObject:GetHandleString(tempD, @"deptId")];
        }
        
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setValue:@"structure" forKey:@"formType"];
        [dataDic setValue:@"ownerDeptId" forKey:@"name"];
        [dataDic setValue:@"3" forKey:@"type"];
        [dataDic setValue:temp forKey:@"values"];
        [array addObject:dataDic];
    }
    
    //    负责人
    if(_chengYuanArray.count > 0){
        NSMutableArray *temp = [NSMutableArray array];
        for (NSDictionary *tempD in _chengYuanArray) {
            [temp addObject:GetHandleString(tempD, @"userId")];
        }
        
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setValue:@"user" forKey:@"formType"];
        [dataDic setValue:@"ownerUserId" forKey:@"name"];
        [dataDic setValue:@"3" forKey:@"type"];
        [dataDic setValue:temp forKey:@"values"];
        [array addObject:dataDic];
    }
    
    [paraDic setValue:array forKey:@"searchList"];
    
    if(_manageResultBlock){
        _manageResultBlock(paraDic);
    }
    
}

//时间筛选
- (IBAction)shiJian:(UIButton *)sender {
    BRDatePickerView *datePickerView = [[BRDatePickerView alloc]init];
    datePickerView.pickerMode = BRDatePickerModeDate;
    datePickerView.title = @"";
    
    if(sender.tag == 501){
        if(_chuangJianJieShuTf.text.length > 0){
            datePickerView.minDate = nil;
            datePickerView.maxDate = [NSDate dateFromString:_chuangJianJieShuTf.text withFormat:@"yyyy-MM-dd"];
        }
    }else  if(sender.tag == 502){
        if(_chuangJianKaiShiTf.text.length > 0){
            datePickerView.minDate = [NSDate dateFromString:_chuangJianKaiShiTf.text withFormat:@"yyyy-MM-dd"];
            datePickerView.maxDate = nil;
        }
    }else  if(sender.tag == 503){
        if(_genJinJieShuTf.text.length > 0){
            datePickerView.minDate = nil;
            datePickerView.maxDate = [NSDate dateFromString:_genJinJieShuTf.text withFormat:@"yyyy-MM-dd"];
        }
    }else  if(sender.tag == 504){
        if(_genJinKaiShiTf.text.length > 0){
            datePickerView.minDate = [NSDate dateFromString:_genJinJieShuTf.text withFormat:@"yyyy-MM-dd"];
            datePickerView.maxDate = nil;
        }
    }
    
    datePickerView.isAutoSelect = NO;

    datePickerView.resultBlock = ^(NSDate *selectDate, NSString *selectValue) {
   
        NSLog(@"selectValue=%@", selectValue);
        NSLog(@"selectDate=%@", selectDate);
        NSLog(@"---------------------------------");
        
        
        if(sender.tag == 501){
            _chuangJianKaiShiTf.text = selectValue;
        }else  if(sender.tag == 502){
            _chuangJianJieShuTf.text = selectValue;
        }else  if(sender.tag == 503){
            _genJinKaiShiTf.text = selectValue;
        }else  if(sender.tag == 504){
            _genJinJieShuTf.text = selectValue;
        }
        
    };
 
    
    BRPickerStyle *customStyle = [[BRPickerStyle alloc]init];
    customStyle.pickerColor = [UIColor whiteColor];
    customStyle.selectRowTextColor = rgba(51, 51, 51, 1);
    customStyle.titleBarColor = [UIColor whiteColor];
    customStyle.titleTextColor = [UIColor whiteColor];
    customStyle.cancelTextColor = rgba(153, 153, 153, 1);
    customStyle.doneTextColor = rgba(40, 120, 255, 1);
    customStyle.titleBarHeight = 48;
    customStyle.titleTextFont = [UIFont systemFontOfSize:18];
    datePickerView.pickerStyle = customStyle;
    customStyle.topCornerRadius = 10;
    customStyle.hiddenTitleLine = YES;
    customStyle.separatorColor = rgba(223, 229, 242, 1);
    customStyle.separatorHeight = 0.5;
    customStyle.rowHeight = 64;

    [datePickerView show];
}




- (void)setChengYuanArray:(NSArray *)chengYuanArray{
    _chengYuanArray = chengYuanArray;
}


- (void)setBuMenArray:(NSArray *)buMenArray{
    _buMenArray = buMenArray;
}





//开启tableview的编辑模式
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1) {
        //开启侧滑删除
        return YES;
    }else{
        return NO;
    }
}
//如果想在侧拉的时候显示是中文的删除，只需要用下面的方法替换掉上面的方法就好了
-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewRowAction *deleteRoWAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除客户区域" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){//title可自已定义
 
        
    }];
    return @[deleteRoWAction];
}

//iOS11之后侧滑删除-支持设置图片【设置后iOS11优先走这里，与上面不冲突】
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath  API_AVAILABLE(ios(11.0)){
    //删除
    UIContextualAction *deleteRowAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"delete" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        //删除收货地址
//        YZMyAddressListModel *modelCell =self.dataSouce[indexPath.row];
//        [self deleteAddressWithModel:modelCell];
//        //刷新表格
//        [self.dataSouce removeObject:modelCell];//删除数据源当前行数据
//        //        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//        [self.tableView reloadData];
//        //空白页处理
//        if (self.dataSouce.count>0) {
//            self.noDataView.hidden = YES;
//        }else{
//            self.noDataView.hidden = NO;
//        }
        completionHandler (YES);
    }];
    deleteRowAction.image = [UIImage imageNamed:@"删除客户区域"];
    deleteRowAction.backgroundColor = [UIColor whiteColor];

    UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[deleteRowAction]];
    return config;
}

@end
